package auth_r

import (
	"encoding/json"
	"frozen-go-mini/common/domain"
	"frozen-go-mini/common/mycontext"
	"frozen-go-mini/cv/user_cv"
	"frozen-go-mini/domain/user_m"
	"frozen-go-mini/resp"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"io"
	"net/http"
)

type AuthByCodeReq struct {
	Code string `json:"code" binding:"required"`
}

// @Tags 授权
// @Summary 根据code微信授权
// @Param Authorization header string true "token"
// @Param AuthByCodeReq body AuthByCodeReq true "code"
// @Success 200 {object} user_cv.User
// @Router /v1.0/auto/code [POST]
func AuthByCode(c *gin.Context) (*mycontext.MyContext, error) {
	myCtx := mycontext.CreateMyContext(c.Keys)
	model := domain.CreateModelContext(myCtx)
	var param AuthByCodeReq
	if err := c.ShouldBindJSON(&param); err != nil {
		return myCtx, err
	}
	code := param.Code
	url := "https://api.weixin.qq.com/sns/jscode2session?appid=wx87e71a8a7bbc5ef5&secret=4375222efa7594cabf0ff906bc84ad97&grant_type=authorization_code" +
		"&js_code=" + code
	method := "GET"

	client := &http.Client{}
	req, err := http.NewRequest(method, url, nil)

	if err != nil {
		return myCtx, err
	}
	res, err := client.Do(req)
	if err != nil {
		return myCtx, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		return myCtx, err
	}
	type Result struct {
		SessionKey string `json:"session_key"`
		Openid     string `json:"openid"`
		Errcode    int    `json:"errcode"`
		Errmsg     string `json:"errmsg"`
	}
	var result Result
	if err := json.Unmarshal(body, &result); err != nil {
		return myCtx, err
	}
	if result.Errcode != 0 {
		return myCtx, errors.New(result.Errmsg)
	}
	user, err := user_m.GetSetUserByOpenId(model, result.Openid)
	if err != nil {
		return myCtx, err
	}
	// 入库
	resp.ResponseOk(c, user_cv.User{
		Id:     user.ID,
		Avatar: user.Avatar,
		Nick:   user.Nick,
	})
	return myCtx, nil
}
